package com.sdy.dcsb.web.controller.inboundservice.util;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import javax.xml.soap.MimeHeaders;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.util.*;
import static org.springframework.util.StringUtils.isEmpty;

/**
 * <p>
 *  处理HTTP请求的IP、请求包头、请求body等信息
 * </p>
 *
 * @author fb
 * @since 2019-10-28
 */
@Slf4j
public class ServletUtil {

    /**
     * 获取HTTP请求的请求IP
     * @param request
     * @return
     */
    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("X-Real-IP");
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Forwarded-For");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        // 处理多IP的情况（只取第一个IP）
        if(ip != null && ip.contains(",")) {
            String[] ipArray = ip.split(",");
            ip = ipArray[0];
        }
        if("0:0:0:0:0:0:0:1".equals(ip)) {
            try {
                ip = InetAddress.getLocalHost().getHostAddress();
            }catch (Exception e) {
                ip = "127.0.0.1";
            }
        }
        return ip;
    }

    /**
     * 获取HTTP请求包头信息
     * @param request
     * @return
     */
    @SuppressWarnings("unchecked")
    public static MimeHeaders getHeaders(HttpServletRequest request) {
        Enumeration<String> enumt = request.getHeaderNames();
        MimeHeaders headers = new MimeHeaders();
        while (enumt.hasMoreElements()) {
            String headerName = enumt.nextElement();
            String headerValue = request.getHeader(headerName);
            StringTokenizer values = new StringTokenizer(headerValue, ",");
            while (values.hasMoreTokens()) {
                headers.addHeader(headerName, values.nextToken().trim());
            }
        }
        return headers;
    }

    public static HashMap<String, String> headerMap(HttpServletRequest request) {
        Enumeration<String> enumt = request.getHeaderNames();
        HashMap<String, String> map = new HashMap<String, String>();
        while (enumt.hasMoreElements()) {
            String headerName = enumt.nextElement();
            String headerValue = request.getHeader(headerName);
            if("content-length".equalsIgnoreCase(headerName)){

            }else if("host".equalsIgnoreCase(headerName)){

            }else if("user-agent".equalsIgnoreCase(headerName)){

            }else if("req_type".equalsIgnoreCase(headerName)){

            }else if("content-type".equalsIgnoreCase(headerName)){
            // 去除nginx的头信息
            }else if("X-Real-IP".equalsIgnoreCase(headerName)){

            }else if("X-Forwarded-For".equalsIgnoreCase(headerName)){

            }else if("X-Forwarded-Proto".equalsIgnoreCase(headerName)){

            }else if("connection".equalsIgnoreCase(headerName)){
            // 去除postman的头信息
            }else if("accept-encoding".equalsIgnoreCase(headerName)){

            }else if("accept".equalsIgnoreCase(headerName)){

            }else {
                map.put(headerName,headerValue);
            }
        }
        return map;
    }

    /**
     * 获取HTTP请求json的请求参数信息
     * @param request
     * @param encoding
     * @return
     * @throws Exception
     */
    public static String getReqBodyString(HttpServletRequest request, String encoding) throws Exception {
        BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream(), encoding));
        StringBuffer sb = new StringBuffer();
        String line = null;
        try {
            while((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            throw e;
        }
        return sb.toString();
    }

    /**
     * 获取HTTP请求form表单的请求参数信息
     * @param request
     * @param encoding
     * @return
     * @throws Exception
     */
    public static String getReqFormBodyString(HttpServletRequest request, String encoding) throws Exception {
//        BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream(), encoding));
//        System.out.println("reader："+reader.readLine());
//        System.out.println("reader："+reader.readLine());
//
//        StringBuffer sb = new StringBuffer();
//        String line = null;
//        try {
//            while((line = reader.readLine()) != null) {
//                sb.append(line+"\r\n");
//            }
//        } catch (IOException e) {
//            throw e;
//        }
//        return sb.toString();

        String reqMsg = "";
        String key = "";
        String value = "";
        StringBuffer sb = new StringBuffer();
        Iterator<String> it = request.getParameterMap().keySet().iterator();
        while(it.hasNext()) {
            key = it.next();
            value = (request.getParameterMap().get(key))[0].toString();
            sb.append(key + "=" + value + "&");
        }
        reqMsg = sb.toString();
        if(!isEmpty(reqMsg)) {
            reqMsg = reqMsg.substring(0,reqMsg.lastIndexOf("&"));
        }
        return reqMsg;
    }

    /**
     * 获取HTTP请求urlencoded的请求参数信息
     * @param request
     * @param contentType
     * @param charset
     * @return
     * @throws Exception
     */
    public static String readReqBody(HttpServletRequest request, String contentType, String charset)
            throws Exception {
        String reqMsg = "";
        if(charset.equals(contentType)) {
            charset = "UTF-8";
        }
        if(null != contentType
                && contentType.length() > 0
                && contentType.contains("application/x-www-form-urlencoded")) {
            String key = "";
            String value = "";
            StringBuffer sb = new StringBuffer();
            Iterator<String> it = request.getParameterMap().keySet().iterator();
            while(it.hasNext()) {
                key = it.next();
                value = (request.getParameterMap().get(key))[0].toString();
                sb.append(key + "=" + value + "&");
            }
            reqMsg = sb.toString();
            if(!isEmpty(reqMsg)) {
                reqMsg = reqMsg.substring(0,reqMsg.lastIndexOf("&"));
            }
        }else {
            reqMsg = ServletUtil.getReqBodyString(request, charset);
        }
        return reqMsg;
    }

}
